import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:dio/dio.dart';
import 'dart:convert';
import './Data.dart';

class AddCook extends StatefulWidget {
  AddCook({
    Key key,
    @required this.text, // 接收一个text参数
  }) : super(key: key);
  final String text;
  @override
  AddCookState createState() => new AddCookState(this.text);
}

class AddCookState extends State<AddCook> {
  String text;
  AddCookState(this.text);
  Dio dio = Dio();

  // 图片地址
  String imgUrl = '';
  // 标题
  String title = '';
  // 描述
  String desc = '';
  Map classify = {"id": 0, "name": ""};
  // 材料
  var materialList = <Widget>[];
  List materialListValue = [];
  // 步骤
  List<Widget> stepList = [];
  List stepListValue = [];

  Widget materialWidget(String item) {
    return Row(
      children: [
        Expanded(
            child: TextField(
          decoration: InputDecoration(
            labelText: "材料名称",
            hintText: "名称",
          ),
          keyboardType: TextInputType.text,
          obscureText: false,
          onChanged: (value) => inputMaterailInfo('name', value, item),
        )),
        Expanded(
            child: TextField(
          decoration: InputDecoration(
            labelText: "材料数量",
            hintText: "数量",
          ),
          keyboardType: TextInputType.number,
          obscureText: false,
          onChanged: (value) => inputMaterailInfo('num', value, item),
        )),
        OutlineButton.icon(
          icon: Icon(Icons.delete),
          label: Text("删除"),
          onPressed: () => removeMaterial(item),
        )
      ],
    );
  }

  Widget stepWidget(String item) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text("${'步骤' + item}"),
            OutlineButton.icon(
              icon: Icon(Icons.delete),
              label: Text("删除"),
              onPressed: () => removeStepItem(item),
            ),
          ],
        ),
        TextField(
          decoration: InputDecoration(
            labelText: "图片路径",
            hintText: "图片路径",
          ),
          keyboardType: TextInputType.url,
          obscureText: false,
          onChanged: (value) => inputStepInfo('url', value, item),
        ),
        TextField(
          decoration: InputDecoration(
            labelText: "介绍",
            hintText: "介绍",
          ),
          keyboardType: TextInputType.text,
          obscureText: false,
          onChanged: (value) => inputStepInfo('name', value, item),
        ),
      ],
    );
  }

  // 分类数据
  List categoryData = [];
  Future getData() async {
    final String url = 'http://127.0.0.1:7001/category/getAll';
    final res = await dio.get(url);
    var data = jsonDecode(res.toString());
    categoryData = data['data']
        .map((i) => CategoryList.fromJson(i.cast<String, dynamic>()))
        .toList();
    print(categoryData);
    setState(() {
      getMaterialWidget();
    });
  }

  @override
  initState() {
    super.initState();
    getData();
  }

  List<Widget> getMaterialWidget() {
    List data = [];
    data.add({'name': 'smal', 'id': 1});
    return data.map((e) => getcategoryWidgetList(e)).toList();
  }

  Widget getcategoryWidgetList(e) {
    return SimpleDialogOption(
      onPressed: () {
        this.classify['id'] = e['id'];
        this.classify['name'] = e['name'];
        Navigator.pop(context, e['id']);
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 6),
        child: Text(e['name']),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("创建食谱"),
          actions: [
            IconButton(icon: Icon(Icons.done), onPressed: () => confirmData())
          ],
        ),
        body: SingleChildScrollView(
            child: Container(
                padding: const EdgeInsets.all(20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
                      child: Text(
                        "图片地址",
                        style: TextStyle(
                            fontSize: 22, fontWeight: FontWeight.bold),
                      ),
                    ),
                    Container(
                        child: TextField(
                      autofocus: true,
                      onChanged: (value) => this.imgUrl = value,
                      keyboardType: TextInputType.url,
                      decoration:
                          InputDecoration(labelText: "图片地址", hintText: "图片地址"),
                    )),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
                      child: Text(
                        "标题",
                        style: TextStyle(
                            fontSize: 22, fontWeight: FontWeight.bold),
                      ),
                    ),
                    TextField(
                      keyboardType: TextInputType.text,
                      decoration: InputDecoration(
                        labelText: "标题",
                        hintText: "食谱标题",
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.blue),
                        ),
                      ),
                      obscureText: false,
                      onChanged: (value) => this.title = value,
                    ),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
                      child: Text(
                        "介绍",
                        style: TextStyle(
                            fontSize: 22, fontWeight: FontWeight.bold),
                      ),
                    ),
                    TextField(
                        keyboardType: TextInputType.text,
                        decoration: InputDecoration(
                          labelText: "介绍",
                          hintText: "食谱介绍",
                          focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(color: Colors.blue),
                          ),
                        ),
                        obscureText: false,
                        onChanged: (value) => this.desc = value),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
                      child: Text(
                        "分类",
                        style: TextStyle(
                            fontSize: 22, fontWeight: FontWeight.bold),
                      ),
                    ),
                    GestureDetector(
                      child: Container(
                        padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
                        child: Row(
                          children: [Text("选中分类："), Text(classify['name'])],
                        ),
                      ),
                      onTap: () => selectClassify(),
                    ),
                    Padding(
                        padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              "材料",
                              style: TextStyle(
                                  fontSize: 22, fontWeight: FontWeight.bold),
                            ),
                            OutlineButton.icon(
                              icon: Icon(Icons.add),
                              label: Text("添加"),
                              onPressed: () => addMaterial(),
                            ),
                          ],
                        )),
                    Column(children: materialList),
                    Padding(
                      padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            "步骤",
                            style: TextStyle(
                                fontSize: 22, fontWeight: FontWeight.bold),
                          ),
                          OutlineButton.icon(
                            icon: Icon(Icons.add),
                            label: Text("添加"),
                            onPressed: () => addStep(),
                          ),
                        ],
                      ),
                    ),
                    Column(children: stepList)
                  ],
                ))));
  }

// 弹出对话框
  Future<bool> showDeleteConfirmDialog1(String text) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("提示"),
          content: Text(text),
          actions: <Widget>[
            FlatButton(
              child: Text("取消"),
              onPressed: () => Navigator.of(context).pop(), // 关闭对话框
            ),
            FlatButton(
              child: Text("确认"),
              onPressed: () {
                //关闭对话框并返回true
                Navigator.of(context).pop(true);
              },
            ),
          ],
        );
      },
    );
  }

  void inputImageUrl(String value) {}

  // ignore: non_constant_identifier_names
  void inputMaterailInfo(String name, String value, String item) {
    int index = int.parse(item);
    materialListValue[index][name] = value;
  }

  void addMaterial() {
    setState(() {
      materialListValue.add({'name': '', 'num': ''});
      materialList.add(materialWidget(materialList.length.toString()));
    });
  }

  void removeMaterial(item) {
    setState(() {
      materialList.removeLast();
      materialListValue.removeLast();
    });
  }

  void addStep() {
    setState(() {
      stepListValue.add({'name': '', 'num': ''});
      int len = stepList.length + 1;
      stepList.add(stepWidget(len.toString()));
    });
  }

  void inputStepInfo(String name, String value, String item) {
    int index = int.parse(item);
    stepListValue[index][name] = value;
  }

  void removeStepItem(String item) {
    int index = int.parse(item) - 1;
    print(index);
    setState(() {
      stepList.remove(stepList[index]);
      stepListValue.remove(stepListValue[index]);
    });
  }

  Future confirmData() async {
    String text;

    if (this.imgUrl.length < 1) {
      text = '请输入图片路径';
    } else if (this.title.length < 1) {
      text = "请输入食谱标题";
    } else if (this.desc.length < 1) {
      text = '请输入食谱描述';
    } else if (this.materialListValue.length < 1) {
      text = '请输入食谱材料';
    } else if (this.stepListValue.length < 1) {
      text = '请输入制作步骤';
    }
    //弹出对话框并等待其关闭
    if (text != null) {
      bool delete = await showDeleteConfirmDialog1(text);
      if (delete == null) {
        print("取消");
      } else {
        print("已确认");
      }
    } else {
      bool delete = await showDeleteConfirmDialog1('是否确认提交数据');
      if (delete == null) {
        print("取消");
      } else {
        final String url = 'http://127.0.0.1:7001/cook/add';
        final res = await dio.post(url, data: {
          "name": this.title,
          "desc": this.desc,
          "cover": this.imgUrl,
          "steps": this.stepListValue,
          "materials": this.materialListValue,
          "category_id": this.classify['id'],
          "user_id": 1
        });
        print(res);
        await showDeleteConfirmDialog1('插入成功');
      }
    }
  }

  // 选择分类
  Future<void> selectClassify() async {
    var i = await showDialog<int>(
        context: context,
        builder: (BuildContext context) {
          return SimpleDialog(
            title: const Text('请选择分类'),
            children: getMaterialWidget(),
          );
        });
    print(i);
    if (i != null) {
      setState(() {});
    }
  }
}
